package com.sendables;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;

import util.Util;

import com.exception.IllegalPackageException;

public class MultiPointLine extends Paintable {
	private ArrayList<DoodlePoint>	pList;

	public MultiPointLine(int ownerId, Color c, DoodlePoint start)
	{
		super(ownerId, c, start);
		pList = new ArrayList<DoodlePoint>();
	}

	public MultiPointLine()
	{
		super();
	}

	public void addPoint(DoodlePoint p)
	{
		pList.add(p);
	}

	public void paint(Graphics g)
	{
		if (pList.size() < 1)
		{
			return;
		}
		g.setColor(c);
		g.drawLine(start.getX(), start.getY(), pList.get(0).getX(), pList.get(0).getY());
		g.drawLine(start.getX(), start.getY() - 1, pList.get(0).getX(), pList.get(0).getY() - 1);
		for (int i = 0; i < pList.size() - 1; i++)
		{
			DoodlePoint start = pList.get(i);
			DoodlePoint to = pList.get(i + 1);
			g.drawLine(start.getX(), start.getY(), to.getX(), to.getY());
			g.drawLine(start.getX(), start.getY() - 1, to.getX(), to.getY() - 1);
		}

	}

	@Override
	public void writeByteRepresentation(byte[] b, int[] offset)
	{
		b[offset[0]++] = Sendable.MULTI_POINT_LINE;
		super.writeByteRepresentation(b, offset);
		new Number(pList.size()).writeByteRepresentation(b, offset);
		for (DoodlePoint dp : pList)
		{
			dp.writeByteRepresentation(b, offset);
		}
		Util.print(b, " ");
	}

	public String toString()
	{
		StringBuilder sb = new StringBuilder();
		sb.append(getClass().getCanonicalName() + super.toString());
		for (DoodlePoint dp : pList)
		{
			sb.append(dp + ", ");
		}
		return sb.toString();
	}

	public Sendable parse(byte[] b, int[] offset) throws IllegalPackageException
	{
		if (b[offset[0]++] != Sendable.MULTI_POINT_LINE)
			throw new IllegalPackageException(
					"Trying to parse something that isnt a MultiPointLine in class: MultiPointLine");
		parseSuper(b, offset);
		pList = new ArrayList<DoodlePoint>();
		int nbrToParse = Number.parse(b, offset).getContent();
		System.out.println(nbrToParse);
		while (nbrToParse > 0)
		{
			pList.add(DoodlePoint.parse(b, offset));
			nbrToParse--;
		}
		return this;
	}

//	public static void main(String[] args) throws IllegalPackageException
//	{
//		MultiPointLine mpl = new MultiPointLine(3434, Color.RED, new DoodlePoint(881, 283));
//		mpl.addPoint(new DoodlePoint(28372, 232));
//		mpl.addPoint(new DoodlePoint(34, 163));
//		mpl.addPoint(new DoodlePoint(347, 14));
//		mpl.addPoint(new DoodlePoint(8345, 34));
//		byte[] b = new byte[mpl.getAlloc()];
//		mpl.writeByteRepresentation(b, new int[] { 0 });
//		MultiPointLine mpll = (MultiPointLine) new MultiPointLine().parse(b, new int[] { 0 });
//		System.out.println(mpl);
//		System.out.println(mpll);
//	}

	@Override
	public int getAlloc()
	{
		return (pList.size() * pList.get(0).getAlloc()) + alloc(pList.size()) + super.getAlloc();
	}

}
